package shiro;

import domain.entity.UserInfos;
import domain.entity.base.UserInfo;
import domain.service.user.UserInfosService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

/**
 * Created by bowen on 2017-08-21.
 */
public class TenantRealm extends AuthorizingRealm {

    private static final Logger logger = LoggerFactory.getLogger(TenantRealm.class);

    private Session session = null;

    private UserInfo userInfo = null;

    @Autowired
    private UserInfosService userInfosService;

    public void start() {
        Subject subject = SecurityUtils.getSubject();
        session = subject.getSession();
        userInfo = (UserInfo) session.getAttribute("user");
    }

    public AuthorizationInfo getBySession() {
        start();
        Object obj = session.getAttribute("authorizationInfo" + userInfo.getNickname());
        if (obj != null)
            return (SimpleAuthorizationInfo) obj;
        else {
            return getAuthorizationInfo();
        }
    }

    protected AuthorizationInfo getAuthorizationInfo() {
        start();
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        session.setAttribute("authorizationInfo" + userInfo.getNickname(), info);
        return info;
    }


    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        return getBySession();
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        return loginByUser(token);
    }

    /**
     * 通过用户名登录
     *
     * @param authenticationToken
     * @return
     */
    protected AuthenticationInfo loginByUser(AuthenticationToken authenticationToken) {
        UsernamePasswordToken token = (UsernamePasswordToken) authenticationToken;
        String password = new String(token.getPassword());
        UserInfos userInfo = new UserInfos();
        userInfo.setUSERNAME(token.getUsername());
        userInfo.setPWD(password);
        Long userId = userInfosService.getUserInfo(userInfo);
        logger.info("========TenantRealm_userInfo===========" + token.getUsername() + "");
        if (userId == null) {
            return new SimpleAuthenticationInfo(userInfo.getUSERNAME(),userInfo.getPWD(), getName());
        }
        return null;
    }
}
